package com.ruoyi.back.service.impl

import cn.hutool.core.util.StrUtil
import com.baomidou.mybatisplus.extension.kotlin.KtQueryWrapper
import com.baomidou.mybatisplus.extension.plugins.pagination.Page
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
import com.ruoyi.app.common.Data
import com.ruoyi.app.common.Ok
import com.ruoyi.back.domain.ClubJob
import com.ruoyi.back.mapper.ClubJobMapper
import com.ruoyi.back.service.ClubJobDataService
import com.ruoyi.back.service.ClubJobService
import com.ruoyi.common.core.page.TableSupport
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service

@Service
class ClubJobServiceImpl : ServiceImpl<ClubJobMapper, ClubJob>(), ClubJobService {

    @Autowired
    private lateinit var clubJobDataService: ClubJobDataService

    override fun saveClubJob(clubJob: ClubJob): Data<Boolean> =
        clubJob.id?.run {
            Ok("更新成功", updateById(clubJob))
        } ?: kotlin.run {
            Ok("保存成功", save(clubJob))
        }

    override fun clubJobPage(clubJob: ClubJob): Page<ClubJob> =
        TableSupport.buildPageRequest().let { pageDomain ->
            page(Page(pageDomain.pageNum.toLong(), pageDomain.pageSize.toLong()), KtQueryWrapper(ClubJob::class.java)
                .eq(StrUtil.isNotBlank(clubJob.name), ClubJob::name, clubJob.name)
                .orderByDesc(ClubJob::createTime))
                .let { page: Page<ClubJob> ->
                    page.apply {
                        records = page.records.takeIf { it.isNotEmpty() }?.run {
                            map {
                                it.apply {
                                    clubJobDataService.todayCount(it.id!!).run {
                                        exposureCount = first ?: 0
                                        clickCount = second ?: 0
                                    }
                                }
                            }
                        }
                    }
                }
        }


    override fun removeClubJob(cluJobIds: String): Data<Boolean> =
        Ok("批量移除成功", removeByIds(cluJobIds.split(",")))
}